/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.mybatis.plugins.sqlparser.dialect;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.tianyun.cloud.mybatis.plugins.sqlparser.SqlParser;

import java.util.List;

/**
 * Db2
 *
 * @auther ebert_chan
 */
public class Db2DialectParser extends SqlParser {

    /*
     * @see org.tianyun.cloud.mybatis.plugins.sqlparser.SqlParser#setParameters(org.apache.ibatis.session.Configuration,
     * org.apache.ibatis.mapping.BoundSql, java.util.List, int, int)
     */
    @Override
    public void setParameters(Configuration configuration, BoundSql boundSql, List<ParameterMapping> parameterMappings, int pageIndex, int pageSize) {
        long offset = (pageIndex - 1) * pageSize;
        long end = offset + pageSize;
        parameterMappings.add(new ParameterMapping.Builder(configuration, PARAMETER_OFFSET, long.class).build());
        parameterMappings.add(new ParameterMapping.Builder(configuration, PARAMETER_END, long.class).build());
        boundSql.setAdditionalParameter(PARAMETER_OFFSET, offset);
        boundSql.setAdditionalParameter(PARAMETER_END, end);
    }

    /*
     * @see org.tianyun.cloud.mybatis.plugins.sqlparser.SqlParser#toDialectPageSql(java.lang.String)
     */
    @Override
    public String toDialectPageSql(String sql) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("SELECT * FROM (SELECT TEMP_PAGE_PLUGIN.*,ROWNUMBER() OVER() AS PAGEHELPER_ROW_ID FROM ( ");
        sqlBuilder.append(sql);
        sqlBuilder.append(" ) AS TEMP_PAGE_PLUGIN) TEMP_PAGE_PLUGIN WHERE PAGEHELPER_ROW_ID BETWEEN ? AND ?");
        return sqlBuilder.toString();
    }

}
